<template>
  <div class="main">
    <div class="header">
      <Card class="header-content">
        <span class="title">{{ title }}</span>
        <Button icon="md-refresh" type="primary" shape="circle" style="margin-left: 20px;" @click="reload">重新导入</Button>
      </Card>
      <Card class="filter">
        <!-- <Input class="search-input" search enter-button placeholder="" /> -->
        <RadioGroup v-model="condition" size="large">
          <Radio label="按类别"></Radio>
          <Radio label="按方法"></Radio>
          <Radio label="其他"></Radio>
        </RadioGroup>
        <Button class="filter-btn" shape="circle" icon="ios-funnel" size="large">筛选</Button>
      </Card>
    </div>
    <div class="content">
      <Card class="group">
        <Menu mode="vertical" active-name="1" class="group-menu" @on-select="selectGroup">
          <div id="group-menu">
            <MenuItem :name="item.name" v-for="(item, index) in tags" :key="index">{{ item.name + index }}</MenuItem>
          </div>
        </Menu>
      </Card>
      <Card class="select">
        <Transfer
          :titles="titles"
          :data="leftPaths"
          :target-keys="rightPaths"
          :list-style="listStyle"
          :render-format="render3"
          :operations="['撤回', '选取']"
          filterable
          @on-change="handleChange3"
        >
          <div :style="{ float: 'right', margin: '5px' }">
            <Button size="small" @click="reloadMockData">重置</Button>
          </div>
        </Transfer>
      </Card>
      <Card class="export-filter">
        <div style="border-bottom: 1px solid #e9e9e9;padding-bottom:6px;margin-bottom:6px;">
          <Checkbox :indeterminate="indeterminate" :value="checkAll" @click.prevent.native="handleCheckAll">全选</Checkbox>
        </div>
        <CheckboxGroup v-model="checkAllGroup" @on-change="checkAllGroupChange">
          <Checkbox label="接口名称"></Checkbox>
          <Checkbox label="请求参数"></Checkbox>
          <Checkbox label="响应参数"></Checkbox>
          <Checkbox label="请求方法"></Checkbox>
          <Checkbox label="路径"></Checkbox>
          <Checkbox label="参数类型"></Checkbox>
        </CheckboxGroup>
      </Card>
    </div>
    <div class="footer">
      <Card class="description">
        <ButtonGroup size="large" shape="circle">
          <Button icon="ios-eye" type="primary">预览</Button>
          <Button icon="md-download" type="primary" @click="exportData">导出</Button>
        </ButtonGroup>
      </Card>
    </div>
    <Modal class="import-form" v-model="modal" width="50%" height="50%" :closable="false" :mask-closable="false">
      <div style="text-align:center;">
        <Upload
          size="large"
          :format="['json']"
          class="upload-com"
          action="#"
          :max-size="5000"
          :on-format-error="handleFormatError"
          :on-exceeded-size="handleMaxSize"
          :show-upload-list="false"
          :on-success="handleSuccess"
          :before-upload="handleBeforeUpload"
        >
          <Button size="large" icon="ios-cloud-upload-outline">文件导入</Button>
        </Upload>
        <div class="open-url-import">
          <span>开启url导入：</span>
          <i-switch v-model="switch1" @on-change="switchChange" />
        </div>
        <div class="import-url" v-if="switch1">
          <Input placeholder="http://demo.swagger.io/v2/swagger.json" style="width: 300px" />
          <Button type="primary">导入</Button>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script>
// 对象转换数组
import Scrollbar from 'smooth-scrollbar';
function obj2Arr(obj) {
  // console.log('转换前obj', obj);
  let arr = [];
  for (let i in obj) {
    let o = {};
    o[i] = obj[i];
    arr.push(o);
  }
  // console.log('转换后arr', arr);
  return arr;
}
export default {
  name: 'App',
  data() {
    return {
      title: '',
      titles: ['未选接口', '已选接口'],
      modal: true,
      switch1: false,
      condition: '按类别',
      leftPaths: [],
      rightPaths: [],
      listStyle: {
        width: '580px',
        height: '650px',
      },
      indeterminate: true,
      checkAll: false,
      checkAllGroup: ['接口名称', '请求参数', '响应参数', '请求方法', '路径', '参数类型'],
      rawData: null, // 所有接口数据
      tags: [
        {
          name: '全部',
          description: '全部接口',
        },
      ],
      paths: [],
      reportData: [],
    };
  },
  mounted() {
    let data = localStorage.getItem('swagger');
    if (data && data.length > 0) {
      this.loadContent(data);
      this.modal = false;
    } else {
    }
    setTimeout(() => {
      Scrollbar.init(document.querySelector('.group-menu'));
    }, 10);
  },
  methods: {
    reload() {
      localStorage.clear();
      location.reload();
    },
    switchChange() {
      // this.$Message.info('开关状态：' + status);
    },
    handleBeforeUpload(file) {
      // console.log('beforeFile', file);
      this.getFileContent(file);
      return true;
    },
    handleFormatError() {
      this.$Message.error('只支持json格式！');
    },
    handleMaxSize() {
      this.$Message.error('暂时不支持5M以上大小文件！');
    },
    handleSuccess(res, file) {
      // console.log('file', file);
    },
    handleChange3(newTargetKeys) {
      this.rightPaths = newTargetKeys;
    },
    render3(item) {
      return item.label;
    },
    filterMethod(data, query) {
      return data.label.indexOf() > -1;
    },
    loadContent(content) {
      this.rawData = JSON.parse(content);
      // console.log('this.rawData', this.rawData);
      this.title = this.rawData.info.title + '-' + this.rawData.info.version;
      this.tags = this.tags.concat(this.rawData.tags);
      // console.log('tags', this.tags);
      // console.log('this.rawData.paths', this.rawData.paths);
      // 将接口按照不同请求方法进行拆分
      let convertedData = [];
      for (let i in this.rawData.paths) {
        for (let ii in this.rawData.paths[i]) {
          convertedData.push({
            label: i + ' @' + ii + ' #' + this.rawData.paths[i][ii]['summary'],
            key: i + '@' + ii,
            value: this.rawData.paths[i][ii],
            method: ii,
          });
        }
      }
      this.paths = convertedData;
      console.log('this.paths', this.paths);
      this.leftPaths = convertedData;
      // console.log('arr', arr);
      // console.log(this.rawData);
      localStorage.clear();
      localStorage.setItem('swagger', content);
      this.modal = false;
    },
    getFileContent(file) {
      var reader = new FileReader();
      reader.readAsText(file, 'UTF-8');
      reader.onload = function(e) {
        this.loadContent(e.target.result);
      }.bind(this);
    },
    reloadMockData() {
      this.leftPaths = this.paths;
      this.rightPaths = [];
    },
    handleCheckAll() {
      if (this.indeterminate) {
        this.checkAll = false;
      } else {
        this.checkAll = !this.checkAll;
      }
      this.indeterminate = false;

      if (this.checkAll) {
        this.checkAllGroup = ['接口名称', '请求参数', '响应参数', '请求方法', '路径', '参数类型'];
      } else {
        this.checkAllGroup = [];
      }
    },
    checkAllGroupChange(data) {
      if (data.length === 3) {
        this.indeterminate = false;
        this.checkAll = true;
      } else if (data.length > 0) {
        this.indeterminate = true;
        this.checkAll = false;
      } else {
        this.indeterminate = false;
        this.checkAll = false;
      }
    },
    // 传入Schema获取格式化参数
    /*
     * schema
     * type 输入参数 or 输出参数
     */
    getParameFromSchema(schema, type) {
      // console.log('schema', schema);
      let arr = [];
      if (type === 'input') {
        schema.map(t => {
          if (t['schema'] && t['schema']['properties']) {
            let _obj = t['schema']['properties'];
            for (let i in _obj) {
              arr.push({
                parame: i,
                type: _obj[i].type,
                description: _obj[i].description,
              });
            }
          } else {
            arr.push({
              parame: t.name,
              type: t.type,
              description: t.description,
            });
          }
        });
      } else {
        schema.map(t => {
          for (let i in t) {
            if (t[i]['properties']) {
              let _arr = t[i]['properties'];
              for (let ii in _arr) {
                arr.push({
                  parame: ii,
                  type: _arr[ii].type ? _arr[ii].type : '',
                  description: _arr[ii].description ? _arr[ii].description : '',
                });
              }
            } else {
              arr.push({
                parame: i,
                type: t[i].type ? t[i].type : '',
                description: t[i].description ? t[i].description : '',
              });
            }
          }
        });
      }
      return arr;
    },
    selectGroup(tag) {
      this.rightPaths = [];
      // console.log('已选择', tag);
      if (tag === '全部') {
        this.leftPaths = this.paths;
      } else {
        let _filter = this.paths.filter(t => {
          if (t.value.tags[0]) {
            if (t.value.tags[0] === tag) {
              return true;
            }
          }
        });
        this.leftPaths = _filter;
        // console.log('过滤出的接口', _filter)
      }
    },
    exportData() {
      this.reportData = [];
      let _arr = [];
      this.rightPaths.map(t => {
        _arr = _arr.concat(this.paths.filter(el => el.key === t));
      });
      // console.log('执行', _arr);
      _arr.map(t => {
        if (t['value']['responses']['200']) {
          let schemaArr = t['value']['responses']['200']['schema']['$$ref'] ? t['value']['responses']['200']['schema']['$$ref'].split('/') : ''; // schema的$ref分割数组
          this.reportData.push({
            input: this.getParameFromSchema(t['value']['parameters'], 'input'),
            output: this.getParameFromSchema(obj2Arr(t['value']['responses']['200']['schema']['properties']), 'output'),
            schema: schemaArr !== '' ? schemaArr[schemaArr.length - 1] : '',
            title: t.value.summary,
          });
        } else {
          let schemaArr = [];
          for (let i in t['value']['responses']) {
            schemaArr.push({
              description: t['value']['responses'][i],
            });
          }
          this.reportData.push({
            input: this.getParameFromSchema(t['value']['parameters'], 'input'),
            output: schemaArr,
            schema: '',
            title: t.value.summary,
          });
        }
      });
      // console.log('_arr', _arr);
      // console.log('this.reportData', this.reportData);
      localStorage.removeItem('oData');
      localStorage.setItem('oData', JSON.stringify(this.reportData));
      chrome.tabs.create({ url: chrome.runtime.getURL('template/template.html') }, function(tab) {
        // 暂时搁置一个优化：只打开一个唯一的标签页
      });
      // console.log('rightPaths', this.rightPaths);
      // console.log('oData', oData);
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .ivu-modal-footer {
  display: none;
}
/deep/ .ivu-card-body {
  height: 100%;
}
.main {
  height: 100%;
  width: 100%;
  background-color: rgb(236, 238, 241);
  position: absolute;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .header,
  .content,
  .footer {
    width: 100%;
    padding: 10px;
  }
  .header {
    height: 15%;
    // background-color: gray;
    .header-content {
      width: 100%;
      height: 50%;
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      justify-items: center;
      flex-wrap: wrap;
      .title {
        font-size: 20px;
      }
    }
    .filter {
      margin-top: 10px;
      width: 100%;
      height: 50%;
      display: flex;
      justify-content: flex-start;
      // .search-input {
      //   width: 400px;
      // }
      .filter-btn {
        margin-left: 20px;
      }
    }
  }
  .content {
    height: 75%;
    // background-color: beige;
    display: flex;
    justify-content: space-around;
    align-items: center;
    .group {
      height: 95%;
      width: auto;
      .group-menu {
        width: 100% !important;
        height: 100% !important;
        overflow-y: scroll;
      }
    }
    .select {
      height: 95%;
      width: 70%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .export-filter {
      height: 95%;
      width: 10%;
    }
  }
  .footer {
    height: 10%;
    // background-color: aqua;
    display: flex;
    justify-content: center;
    align-items: center;
    .description {
      width: 100%;
      height: 95%;
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }
  }
}
.import-form {
  .upload-com,
  .open-url-import {
    margin: 20px;
  }
  .open-url-import {
  }
}
</style>
